/**
 * 
 */
package com.csair.youth.web.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.csair.youth.constant.Constant;
import com.csair.youth.constant.ResourceConstant;
import com.csair.youth.database.Resource;
import com.csair.youth.database.SysConfig;
import com.csair.youth.database.User;
import com.csair.youth.service.impl.CategoryServiceImpl;
import com.csair.youth.service.impl.ResourceServiceImpl;
import com.csair.youth.service.impl.SysConfigServiceImpl;
import com.csair.youth.service.impl.UserServiceImpl;

/**
 * @author mickey
 *
 */
public class ResourceEditAction extends _BaseAction {
	private Resource item;
	private ResourceServiceImpl service;
	private CategoryServiceImpl categoryService;
	private UserServiceImpl userService;
	private SysConfigServiceImpl sysConfigService;
	private String treeString;
	
	public Resource getItem() {
		return item;
	}
	public void setItem(Resource item) {
		this.item = item;
	}
	
	public ResourceServiceImpl getService() {
		return service;
	}
	public void setService(ResourceServiceImpl service) {
		this.service = service;
	}

	public String getTreeString() {
		return treeString;
	}
	public void setTreeString(String treeString) {
		this.treeString = treeString;
	}
	
	public CategoryServiceImpl getCategoryService() {
		return categoryService;
	}
	public void setCategoryService(CategoryServiceImpl categoryService) {
		this.categoryService = categoryService;
	}
	public UserServiceImpl getUserService() {
		return userService;
	}
	public void setUserService(UserServiceImpl userService) {
		this.userService = userService;
	}
	public SysConfigServiceImpl getSysConfigService() {
		return sysConfigService;
	}
	public void setSysConfigService(SysConfigServiceImpl sysConfigService) {
		this.sysConfigService = sysConfigService;
	}
	
	public String execute(){
//		treeString = service.buildCategoryTreeString(service.buildCategoryTree(item != null?item.getId():null, true), "categoryTree", "javascript:setCategory(this, \"categoryTree\");");
		treeString = categoryService.buildCategoryTreeString(categoryService.buildCategoryTree(null, false).get("ROOT"), "categoryTree", "javascript:setCategory(this, \"categoryTree\");");
		if(item != null && !StringUtils.isEmpty(item.getId())){
			//从数据库获取...
			item = service.getResource(item.getId());
			if(item == null){
				item = new Resource();
				item.setId(null);
				return SUCCESS;
			}
			User uploader = userService.getUser(item.getUploadUserId());
			item.setUploadUserName(uploader.getName());
			if(!StringUtils.isEmpty(item.getAuditUserId())){
				User auditor = userService.getUser(item.getAuditUserId());
				item.setAuditUserName(auditor.getName());
			}
		}
		else{
			item.setId(null);  //参数有误
		}
		return SUCCESS;
	}
	
	public String save(){
		if(item == null || StringUtils.isEmpty(item.getId())) {
			this.setMessage("资源对象为空.");
//			treeString = service.buildCategoryTreeString(service.buildCategoryTree(null, false).get("ROOT"), "categoryTree", "javascript:setCategory(this, \"categoryTree\");");
			return INPUT;
		}
		if(!validInput(item)) return INPUT;
		SysConfig httpConfig = sysConfigService.getSysConfigByKey(Constant.SERVER_IP_PORT_KEY);
		SysConfig ftpConfig = sysConfigService.getSysConfigByKey(Constant.SERVER_FTP_KEY);
		Resource db = service.getResource(item.getId());
		db.setFileName(item.getFileName());
		db.setDescription(item.getDescription());
		//如果原来是通过的，本次也是通过的，则需要看是否需要修改category
		if(item.getAuditResult().equals(db.getAuditResult()) && db.getAuditResult().equals(Constant.RESOURCE_AUDIT_PASS)){
			if(!StringUtils.equals(item.getCategoryId(), db.getCategoryId())){
				String categoryPath = categoryService.getCategoryAbsolutePath(item.getCategoryId(), null);
				String categoryPathFtp = categoryService.getCategoryAbsolutePath(item.getCategoryId(), "/");
				String destFileName = System.currentTimeMillis() + "_" + item.getFileName();
				String destPath = ResourceConstant.getInstance().getUploadStorePath() + File.separator + categoryPath + File.separator + destFileName;
				File src = new File(db.getAbsolutePath());
				File dest = new File(destPath);
				try{
					FileUtils.copyFile(src, dest);
					src.delete();
					db.setAbsolutePath(destPath);
					db.setHttpDownAddress(httpConfig.getConfigValue()+"/ResourceDownload.do?p="+item.getId());
					db.setFtpDownAddress(ftpConfig.getConfigValue()+categoryPathFtp+"/"+destFileName);
				}catch(Exception e){
					this.setMessage("资源编辑过程中发生错误[0]");	//copy失败
					return execute();
				}
			}
		}
		//如果原来不是通过的，本次是通过，则需要转移到目标category
		else if(item.getAuditResult().equals(Constant.RESOURCE_AUDIT_PASS) && !db.getAuditResult().equals(Constant.RESOURCE_AUDIT_PASS)){
			String path = db.getAbsolutePath();
			String categoryPath = categoryService.getCategoryAbsolutePath(item.getCategoryId(), null);
			String destPath = ResourceConstant.getInstance().getUploadStorePath() + categoryPath;
			String categoryPathFtp = categoryService.getCategoryAbsolutePath(item.getCategoryId(), "/");
			File dir = new File(destPath);
			if(!dir.exists()){
				boolean suc = dir.mkdirs();
				if(!suc){
					this.setMessage("资源编辑过程中发生错误[1]");	//mkdir失败
					return execute();
				}
			}
			String destFilePath = destPath + File.separator + System.currentTimeMillis()+"_"+item.getFileName();
			String destFileName = System.currentTimeMillis() + "_" + item.getFileName();
			try {
				File src = new File(path);
				File dest = new File(destFilePath);
				FileUtils.copyFile(src, dest);
				src.delete();
				db.setAbsolutePath(destFilePath);
				db.setHttpDownAddress(httpConfig.getConfigValue()+"/ResourceDownload.do?p="+item.getId());
				db.setFtpDownAddress(ftpConfig.getConfigValue()+categoryPathFtp+"/"+destFileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.setMessage("资源编辑过程中发生错误[2]");	//copy失败
			}
		}
		//如果现在是不通过的，而且原来是通过的，则需要转移到tmp目录
		else if(item.getAuditResult().equals(Constant.RESOURCE_AUDIT_FAIL) && db.getAuditResult().equals(Constant.RESOURCE_AUDIT_PASS)){
			String path = db.getAbsolutePath();
			String destPath = ResourceConstant.getInstance().getUploadTmpPath();
			File dir = new File(destPath);
			if(!dir.exists()){
				boolean suc = dir.mkdirs();
				if(!suc){
					this.setMessage("资源编辑过程中发生错误[3]");	//mkdir失败
					return execute();
				}
			}
			String destFilePath = destPath + File.separator + System.currentTimeMillis()+"_"+item.getFileName();
			try {
				File src = new File(path);
				File dest = new File(destFilePath);
				FileUtils.copyFile(src, dest);
				src.delete();
				db.setAbsolutePath(destFilePath);
				db.setHttpDownAddress("");
				db.setFtpDownAddress("");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.setMessage("资源编辑过程中发生错误[4]");	//copy失败
			}
		}
		
		db.setCategoryId(item.getCategoryId());
		if(!StringUtils.equals(db.getAuditRemark(), item.getAuditRemark()) || !StringUtils.equals(db.getAuditResult(), item.getAuditResult())){
			db.setAuditResult(item.getAuditResult());
			db.setAuditRemark(item.getAuditRemark());
			db.setAuditIp(this.getServletRequest().getRemoteAddr());
			db.setAuditUserId((String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY));
			db.setAuditTime(new Date());
		}
		
		db.setLastModifyTime(new Date());
		
		service.saveResource(db);
		this.setMessage("已成功保存资源.");
		return execute();
	}
	
	private boolean validInput(Resource item){
		if(item == null) return false;
		boolean allValid = true;
		StringBuffer msgBf = new StringBuffer();
		String name = item.getFileName();
		if(StringUtils.isEmpty(name) || StringUtils.length(name)> 100){
			msgBf.append("文件名不能为空且必须在100个字符内<br/>");
			allValid = false;
		}
		String desc = item.getDescription();
		if(!StringUtils.isEmpty(desc) && StringUtils.length(desc)> 120){
			msgBf.append("分类描述必须在120个字符内<br/>");
			allValid = false;
		}
		String categoryId = item.getCategoryId();
		if(StringUtils.isEmpty(categoryId)){
			msgBf.append("资源分类不能为空<br/>");
			allValid = false;
		}
		if(categoryService.getCategory(categoryId) == null){
			msgBf.append("资源分类不存在<br/>");
			allValid = false;
		}
		String auditResult = item.getAuditResult();
		if(StringUtils.isEmpty(auditResult)){
			msgBf.append("请选择审核结果<br/>");
			allValid = false;
		}
		String auditRemark = item.getAuditRemark();
		if(!StringUtils.isEmpty(auditRemark) && StringUtils.length(auditRemark)> 120){
			msgBf.append("审核备注必须在120个字符内<br/>");
			allValid = false;
		}
		this.setMessage(msgBf.toString());
		return allValid;
	}
}
